from flask import Blueprint, request, jsonify, current_app
import hashlib
from functools import wraps
from flask import current_app, request, jsonify, Blueprint
from flask_jwt_extended import create_access_token, jwt_required, get_jwt_identity
from . import api_bp



# 从current_app获取db和模型引用
def get_db_and_models():
    db = current_app.db
    User = current_app.User
    Article = current_app.Article
    Banner = current_app.Banner
    Assessment = current_app.Assessment
    return db, User, Article, Banner, Assessment

# 创建管理员API蓝图
admin_bp = Blueprint('admin', __name__)

# 密码哈希函数
def hash_password(password):
    return hashlib.sha256(password.encode('utf-8')).hexdigest()

# 管理员认证装饰器
def admin_required(f):
    @wraps(f)
    @jwt_required()
    def decorated_function(*args, **kwargs):
        # 获取当前登录用户的ID
        current_user_id = get_jwt_identity()
        
        # 获取db和模型引用
        db, User, Article, Banner, Assessment = get_db_and_models()
        
        # 检查用户是否为管理员
        user = User.query.get(current_user_id)
        if not user or not user.is_admin:
            return jsonify({'success': False, 'message': '无管理员权限'}), 403
            
        # 将用户信息添加到请求上下文中
        request.current_user = user
        return f(*args, **kwargs)
    return decorated_function

# 管理员修改自己密码API
@admin_bp.route('/change-password', methods=['PUT'])
@admin_required
def change_admin_password():
    # 获取db和模型引用
    db, User, Article, Banner, Assessment = get_db_and_models()
    
    data = request.json
    if not data or 'old_password' not in data or 'new_password' not in data:
        return jsonify({'success': False, 'message': '缺少必要参数'}), 400
    
    # 获取当前管理员用户
    current_user = request.current_user
    
    # 验证旧密码
    if current_user.password != hash_password(data['old_password']):
        return jsonify({'success': False, 'message': '旧密码错误'}), 401
    
    # 更新新密码
    current_user.password = hash_password(data['new_password'])
    db.session.commit()
    
    return jsonify({'success': True, 'message': '密码修改成功'})

# 超级管理员认证装饰器
def super_admin_required(f):
    @wraps(f)
    @admin_required
    def decorated_function(*args, **kwargs):
        # 检查用户是否为超级管理员
        if request.current_user.admin_level < 2:
            return jsonify({'success': False, 'message': '无超级管理员权限'}), 403
        
        return f(*args, **kwargs)
    return decorated_function

# 管理员登录API
@admin_bp.route('/login', methods=['POST'])
def admin_login():
    # 获取db和模型引用
    db, User, Article, Banner, Assessment = get_db_and_models()
    
    data = request.json
    if not data or 'phone' not in data or 'password' not in data:
        return jsonify({'success': False, 'message': '缺少必要参数'}), 400
    
    # 查找用户
    user = User.query.filter_by(phone=data['phone']).first()
    if not user or not user.is_admin:
        return jsonify({'success': False, 'message': '管理员不存在'}), 404
    
    # 验证密码
    if user.password != hash_password(data['password']):
        return jsonify({'success': False, 'message': '密码错误'}), 401
    
    # 生成JWT访问令牌
    access_token = create_access_token(identity=user.id)
    
    return jsonify({
        'success': True,
        'message': '登录成功',
        'token': access_token,
        'user': {
            'id': user.id,
            'phone': user.phone,
            'nickname': user.nickname,
            'avatar': user.avatar,
            'admin_level': user.admin_level
        }
    })

# 创建管理员账户（仅初始设置时使用，后续可删除）
@admin_bp.route('/create-admin', methods=['POST'])
@super_admin_required
# 注意：此接口现在仅允许超级管理员使用，防止未授权创建超级管理员账户
def create_admin():
    # 获取db和模型引用
    db, User, Article, Banner, Assessment = get_db_and_models()
    
    data = request.json
    if not data or 'phone' not in data or 'password' not in data:
        return jsonify({'success': False, 'message': '缺少必要参数'}), 400
    
    # 检查是否已存在相同手机号的用户
    existing_user = User.query.filter_by(phone=data['phone']).first()
    if existing_user:
        return jsonify({'success': False, 'message': '该手机号已被注册'}), 400
    
    # 创建新管理员账户
    new_admin = User(
        phone=data['phone'],
        password=hash_password(data['password']),
        is_admin=True,
        admin_level=2,  # 默认创建超级管理员
        nickname=data.get('nickname', '超级管理员')
    )
    
    db.session.add(new_admin)
    db.session.commit()
    
    return jsonify({'success': True, 'message': '管理员账户创建成功', 'admin_id': new_admin.id})

# 超级管理员添加普通管理员
@admin_bp.route('/add-admin', methods=['POST'])
@super_admin_required
def add_admin():
    # 获取db和模型引用
    db, User, Article, Banner, Assessment = get_db_and_models()
    
    data = request.json
    if not data or 'phone' not in data or 'password' not in data:
        return jsonify({'success': False, 'message': '缺少必要参数'}), 400
    
    # 检查是否已存在相同手机号的用户
    existing_user = User.query.filter_by(phone=data['phone']).first()
    if existing_user:
        return jsonify({'success': False, 'message': '该手机号已被注册'}), 400
    
    # 创建新普通管理员账户
    new_admin = User(
        phone=data['phone'],
        password=hash_password(data['password']),
        is_admin=True,
        admin_level=1,  # 普通管理员
        nickname=data.get('nickname', '管理员')
    )
    
    db.session.add(new_admin)
    db.session.commit()
    
    return jsonify({'success': True, 'message': '普通管理员账户添加成功', 'admin_id': new_admin.id})

# 超级管理员删除普通管理员
@admin_bp.route('/delete-admin/<int:admin_id>', methods=['DELETE'])
@super_admin_required
def delete_admin(admin_id):
    # 获取db和模型引用
    db, User, Article, Banner, Assessment = get_db_and_models()
    
    # 查找要删除的管理员
    admin_to_delete = User.query.get(admin_id)
    if not admin_to_delete or not admin_to_delete.is_admin:
        return jsonify({'success': False, 'message': '管理员不存在'}), 404
    
    # 不允许删除超级管理员
    if admin_to_delete.admin_level >= 2:
        return jsonify({'success': False, 'message': '不允许删除超级管理员'}), 403
    
    # 不允许删除自己
    if admin_to_delete.id == request.current_user.id:
        return jsonify({'success': False, 'message': '不允许删除自己'}), 403
    
    # 删除管理员
    db.session.delete(admin_to_delete)
    db.session.commit()
    
    return jsonify({'success': True, 'message': '管理员删除成功'})

# 超级管理员更新管理员信息
@admin_bp.route('/update-admin/<int:admin_id>', methods=['PUT'])
@super_admin_required
def update_admin(admin_id):
    # 获取db和模型引用
    db, User, Article, Banner, Assessment = get_db_and_models()
    
    # 查找要更新的管理员
    admin_to_update = User.query.get(admin_id)
    if not admin_to_update or not admin_to_update.is_admin:
        return jsonify({'success': False, 'message': '管理员不存在'}), 404
    
    # 不允许修改超级管理员
    if admin_to_update.admin_level >= 2:
        return jsonify({'success': False, 'message': '不允许修改超级管理员'}), 403
    
    data = request.json
    
    # 更新管理员信息
    if 'nickname' in data:
        admin_to_update.nickname = data['nickname']
    
    if 'password' in data and data['password']:
        admin_to_update.password = hash_password(data['password'])
    
    # 不允许修改自己的管理员级别
    if admin_id != request.current_user.id and 'admin_level' in data:
        # 只能设置为0或1（非管理员或普通管理员）
        if data['admin_level'] in [0, 1]:
            admin_to_update.admin_level = data['admin_level']
            admin_to_update.is_admin = data['admin_level'] > 0
    
    db.session.commit()
    
    return jsonify({'success': True, 'message': '管理员信息更新成功'})

# 文章管理API
@admin_bp.route('/articles', methods=['GET'])
@admin_required
def get_all_articles():
    # 获取db和模型引用
    db, User, Article, Banner, Assessment = get_db_and_models()
    
    articles = Article.query.order_by(Article.created_at.desc()).all()
    result = []
    for article in articles:
        result.append({
            'id': article.id,
            'title': article.title,
            'summary': article.summary,
            'cover_image': article.cover_image,
            'publish_date': article.publish_date,
            'created_at': article.created_at.strftime('%Y-%m-%d %H:%M:%S'),
            'updated_at': article.updated_at.strftime('%Y-%m-%d %H:%M:%S')
        })
    return jsonify({'success': True, 'data': result})

# 轮播图管理API
@admin_bp.route('/banners', methods=['GET'])
@admin_required
def get_all_banners():
    # 获取db和模型引用
    db, User, Article, Banner, Assessment = get_db_and_models()
    
    banners = Banner.query.order_by(Banner.order).all()
    result = []
    for banner in banners:
        result.append({
            'id': banner.id,
            'image_url': banner.image_url,
            'link': banner.link,
            'order': banner.order,
            'created_at': banner.created_at.strftime('%Y-%m-%d %H:%M:%S'),
            'updated_at': banner.updated_at.strftime('%Y-%m-%d %H:%M:%S')
        })
    return jsonify({'success': True, 'data': result})

# 用户管理API
@admin_bp.route('/users', methods=['GET'])
@admin_required
def get_all_users():
    # 获取db和模型引用
    db, User, Article, Banner, Assessment = get_db_and_models()
    
    users = User.query.order_by(User.created_at.desc()).all()
    result = []
    for user in users:
        result.append({
            'id': user.id,
            'phone': user.phone,
            'nickname': user.nickname,
            'avatar': user.avatar,
            'is_admin': user.is_admin,
            'created_at': user.created_at.strftime('%Y-%m-%d %H:%M:%S'),
            'updated_at': user.updated_at.strftime('%Y-%m-%d %H:%M:%S')
        })
    return jsonify({'success': True, 'data': result})

# 评估记录管理API
@admin_bp.route('/assessments', methods=['GET'])
@admin_required
def get_all_assessments():
    # 获取db和模型引用
    db, User, Article, Banner, Assessment = get_db_and_models()
    
    assessments = Assessment.query.order_by(Assessment.created_at.desc()).all()
    result = []
    for assessment in assessments:
        result.append({
            'id': assessment.id,
            'user_id': assessment.user_id,
            'assessment_type': assessment.assessment_type,
            'eyelid_sign': assessment.eyelid_sign,
            'right_eye_protrusion': assessment.right_eye_protrusion,
            'left_eye_protrusion': assessment.left_eye_protrusion,
            'eye_movement': assessment.eye_movement,
            'photo_path': assessment.photo_path,
            'cas_score': assessment.cas_score,
            'treatment_advice': assessment.treatment_advice,
            'status': assessment.status,
            'created_at': assessment.created_at.strftime('%Y-%m-%d %H:%M:%S'),
            'updated_at': assessment.updated_at.strftime('%Y-%m-%d %H:%M:%S')
        })
    return jsonify({'success': True, 'data': result})